/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.Color;
import java.awt.HeadlessException;
import java.io.CharConversionException;
import java.io.IOException;

import javax.swing.JOptionPane;

import negocio.exception.ErroConexaoException;
import negocio.exception.UsuarioJaCadastradoException;

import fachadas.FachadaCliente;

/**
 *
 * @author ACER
 */
public class Janela_Cadastro extends javax.swing.JDialog {

	/**
	 * Creates new form Janela_Cadastro
	 */
	private FachadaCliente fachada;

	public Janela_Cadastro(java.awt.Frame parent, boolean modal, FachadaCliente fachada) {
		super(parent, modal);
		this.fachada = fachada;
		initComponents();
		setLocationRelativeTo(null); 

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jTextField_NomeUsuario = new javax.swing.JTextField();
		jTextField_EmailUsuario = new javax.swing.JTextField();
		jPasswordField_Senha = new javax.swing.JPasswordField();
		jPasswordField_SenhaConfirmacao = new javax.swing.JPasswordField();
		jProgressBar1 = new javax.swing.JProgressBar();
		jButton_OK = new javax.swing.JButton();
		jButton_Cancelar = new javax.swing.JButton();
		jLabel6 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Cadastro de novo Usuario");
		setPreferredSize(new java.awt.Dimension(634, 310));
		setResizable(false);
		getContentPane().setLayout(null);

		jLabel1.setIcon(new javax.swing.ImageIcon("imagens//logo_nome.png")); // NOI18N
		getContentPane().add(jLabel1);
		jLabel1.setBounds(313, 28, 54, 31);

		jLabel2.setIcon(new javax.swing.ImageIcon("imagens//logo_mail.png")); // NOI18N
		getContentPane().add(jLabel2);
		jLabel2.setBounds(313, 65, 54, 29);

		jLabel3.setIcon(new javax.swing.ImageIcon("imagens//logo_senha.png")); // NOI18N
		getContentPane().add(jLabel3);
		jLabel3.setBounds(313, 100, 54, 26);

		jLabel4.setIcon(new javax.swing.ImageIcon("imagens//logo_confirmaSenha.png")); // NOI18N
		getContentPane().add(jLabel4);
		jLabel4.setBounds(310, 160, 178, 34);
		getContentPane().add(jTextField_NomeUsuario);
		jTextField_NomeUsuario.setBounds(371, 39, 180, 20);

		jTextField_EmailUsuario.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField_EmailUsuarioActionPerformed(evt);
			}
		});
		getContentPane().add(jTextField_EmailUsuario);
		jTextField_EmailUsuario.setBounds(371, 74, 180, 20);

		jPasswordField_Senha.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jPasswordField_SenhaActionPerformed(evt);
			}
		});
		jPasswordField_Senha.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jPasswordField_SenhaKeyPressed(evt);
			}
		});
		getContentPane().add(jPasswordField_Senha);
		jPasswordField_Senha.setBounds(371, 106, 180, 20);

		jPasswordField_SenhaConfirmacao.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jPasswordField_SenhaConfirmacaoKeyPressed(evt);
			}
		});
		getContentPane().add(jPasswordField_SenhaConfirmacao);
		jPasswordField_SenhaConfirmacao.setBounds(310, 200, 240, 20);

		jProgressBar1.setMaximumSize(new java.awt.Dimension(40, 17));
		jProgressBar1.setStringPainted(true);
		jProgressBar1.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jProgressBar1KeyPressed(evt);
			}
		});
		getContentPane().add(jProgressBar1);
		jProgressBar1.setBounds(310, 140, 240, 17);
		
		this.jProgressBar1.setStringPainted(true);

		jButton_OK.setText(" Cadastrar");
		jButton_OK.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton_OKActionPerformed(evt);
			}
		});
		getContentPane().add(jButton_OK);
		jButton_OK.setBounds(340, 230, 83, 23);

		jButton_Cancelar.setText("Cancelar");
		jButton_Cancelar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton_CancelarActionPerformed(evt);
			}
		});
		getContentPane().add(jButton_Cancelar);
		jButton_Cancelar.setBounds(440, 230, 75, 23);

		jLabel6.setIcon(new javax.swing.ImageIcon("imagens//logo_add.png")); // NOI18N
		getContentPane().add(jLabel6);
		jLabel6.setBounds(10, 40, 300, 197);

		jLabel5.setIcon(new javax.swing.ImageIcon("imagens//logo_fundo.jpg")); // NOI18N
		getContentPane().add(jLabel5);
		jLabel5.setBounds(-60, -540, 1210, 1070);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void jTextField_EmailUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_EmailUsuarioActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jTextField_EmailUsuarioActionPerformed

	private void jPasswordField_SenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField_SenhaActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jPasswordField_SenhaActionPerformed

	private void jButton_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OKActionPerformed
		if(evt.getSource() == jButton_OK){

			boolean tudoOk = true;
			boolean jaExiste = false;
			boolean senhaIgual = true;
			
			String nome = jTextField_NomeUsuario.getText().trim();
			String email = jTextField_EmailUsuario.getText().trim();

			char[] senha = jPasswordField_Senha.getPassword();
			char[] conf_senha = jPasswordField_SenhaConfirmacao.getPassword();

			String senha2 = "" ;
			for(int i = 0; i < senha.length ; i++){
				senha2 += senha[i];
			}

			String conf_senha2 = "" ;
			for(int i = 0; i < conf_senha.length; i++){
				conf_senha2 += conf_senha[i];
			}

			if((nome.equals("")) || (email.equals("")) || (senha2.equals("")) || (conf_senha2.equals(""))){
				JOptionPane.showMessageDialog(null, "Campos obrigatorios nao preenchidos!", "Atencao!", JOptionPane.WARNING_MESSAGE);
				tudoOk = false;
			}

			if(!(senha2.equals(conf_senha2))){
				JOptionPane.showMessageDialog(null, "As senhas nao conferem!\nFavor redigi-las!" ,"Atencao!", JOptionPane.WARNING_MESSAGE);
				jPasswordField_Senha.setText("");
				jPasswordField_SenhaConfirmacao.setText("");
				tudoOk = false;
			}

			//Procurar se ja existe usuario com o email repassado.
			if(jaExiste){
				JOptionPane.showMessageDialog(null, "Nao se pode usar o mesmo email de um cliente ja cadastrado!" ,"Atencao!", JOptionPane.WARNING_MESSAGE);
				jTextField_EmailUsuario.setText("");
				tudoOk = false;
			}

			if(tudoOk){
				//Tudo dando certo, chama o metodo para cadastrar e abre um dialogo dando o ok.
				
				try {
					if(this.fachada.cadastrarUsuario(nome, email, senha2)){
						JOptionPane.showMessageDialog(null, "Usuario cadastrado com sucesso!");
					} else{
						JOptionPane.showMessageDialog(null, "Erro tipo: Algo ocorreu de errado no servidor.", "Erro!", JOptionPane.ERROR_MESSAGE);
					}
				} catch (ClassNotFoundException e) {
					JOptionPane.showMessageDialog(null, "Erro tipo: "+e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
				} catch (UsuarioJaCadastradoException e) {
					JOptionPane.showMessageDialog(null, "Erro tipo: "+e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, "Erro tipo: "+e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
				} catch (HeadlessException e) {
					JOptionPane.showMessageDialog(null, "Erro tipo: "+e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
				} catch (ErroConexaoException e) {
					JOptionPane.showMessageDialog(null, "Erro tipo: "+e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
				}								
				this.setVisible(false);
				
			}
		}
	}//GEN-LAST:event_jButton_OKActionPerformed

	private void jButton_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelarActionPerformed
		if(evt.getSource() == jButton_Cancelar){
			this.setVisible(false);
		}
	}//GEN-LAST:event_jButton_CancelarActionPerformed

	private void jProgressBar1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jProgressBar1KeyPressed
		char[] senha = jPasswordField_Senha.getPassword();
		for(int i = 0; i < senha.length ; i++){
			if(senha.length < 7){
				jProgressBar1.setValue(15);
			}
		}
	}//GEN-LAST:event_jProgressBar1KeyPressed

	private void jPasswordField_SenhaConfirmacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_SenhaConfirmacaoKeyPressed
		// TODO add your handling code here:
	}//GEN-LAST:event_jPasswordField_SenhaConfirmacaoKeyPressed

	private void jPasswordField_SenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_SenhaKeyPressed

		if(evt.getSource() == jPasswordField_Senha){
			int len = jPasswordField_Senha.getPassword().length + 1;
			char[] x = new char[len];
			if(len > 1) System.arraycopy(jPasswordField_Senha.getPassword(), 0, x, 0, len-1);
			x[len - 1] = evt.getKeyChar();            

			boolean temNum = false;
			boolean temChar = false;
			boolean temMaius = false;

			for(int i = 0; i < x.length ; i++){
				if(Character.isUpperCase(x[i])){
					temMaius = true;
				}
				if(Character.isDigit(x[i])){
					temNum = true;
				}
				if(!Character.isLetterOrDigit(x[i])){
					temChar = true;
				}

			}
			if(x.length == 0){
				jProgressBar1.setValue(0);
				jProgressBar1.setString("Muito fraca");
				jProgressBar1.setForeground(Color.RED);
			}else if(x.length < 4){
				if(temNum || temChar || temMaius){
					jProgressBar1.setValue(13);
					jProgressBar1.setString("Muito fraca");
					jProgressBar1.setForeground(Color.RED);
				} else{
					jProgressBar1.setValue(3);
					jProgressBar1.setString("Muito fraca");
					jProgressBar1.setForeground(Color.RED);
				}
			}else if(x.length < 7){
				if(temNum || temChar || temMaius){
					jProgressBar1.setValue(24);
					jProgressBar1.setString("Fraca");
					jProgressBar1.setForeground(Color.ORANGE);
				}else{
					jProgressBar1.setValue(10);
					jProgressBar1.setString("Muito fraca");
					jProgressBar1.setForeground(Color.RED);
				}
			}else if(x.length < 11){
				if(temNum || temChar || temMaius){
					jProgressBar1.setValue(36);
					jProgressBar1.setString("Boa");
					jProgressBar1.setForeground(Color.YELLOW);
				}else{
					jProgressBar1.setValue(20);
					jProgressBar1.setString("Fraca");
					jProgressBar1.setForeground(Color.ORANGE);
				}
			}else if(x.length < 14){
				if(x.length < 14 && (temNum || temChar || temMaius)){
					jProgressBar1.setValue(48);
					jProgressBar1.setString("Boa");
					jProgressBar1.setForeground(Color.YELLOW);
					if(x.length < 14 && ((temNum && temChar) || (temNum && temMaius) || (temMaius && temChar))){
						jProgressBar1.setValue(59);
						jProgressBar1.setString("Boa");
						jProgressBar1.setForeground(Color.YELLOW);
					}
				}else{
					jProgressBar1.setValue(30);
					jProgressBar1.setString("Fraca");
					jProgressBar1.setForeground(Color.ORANGE);
				}
			}else if(x.length < 17){
				if(temNum || temChar || temMaius){
					jProgressBar1.setValue(60);
					jProgressBar1.setString("Boa");
					jProgressBar1.setForeground(Color.YELLOW);
					if((temNum && temChar) || (temNum && temMaius) || (temMaius && temChar)){
						jProgressBar1.setValue(79);
						jProgressBar1.setString("Forte");
						jProgressBar1.setForeground(Color.BLUE);
					}
				}else{
					jProgressBar1.setValue(40);
					jProgressBar1.setString("Boa");
					jProgressBar1.setForeground(Color.YELLOW);
				}
			}else if(x.length >= 20){
				if((temNum || temChar || temMaius)){
					jProgressBar1.setValue(88);
					jProgressBar1.setString("Muito Forte");
					jProgressBar1.setForeground(Color.BLUE);
					if((temNum && temChar) || (temNum && temMaius) || (temMaius && temChar)){
						jProgressBar1.setValue(96);
						jProgressBar1.setString("Muito Forte");
						jProgressBar1.setForeground(Color.GREEN);
					}
				} else{   
					jProgressBar1.setValue(50);
					jProgressBar1.setString("Boa");
					jProgressBar1.setForeground(Color.YELLOW);
				}
			}else if(x.length >= 20){
				jProgressBar1.setValue(100);
				jProgressBar1.setString("Muito Forte");
				jProgressBar1.setForeground(Color.GREEN);
				if(temNum && temChar && temMaius){
					jProgressBar1.setValue(100);
					jProgressBar1.setString("Muito Forte");
					jProgressBar1.setForeground(Color.GREEN);
				}
			}
		}
	}//GEN-LAST:event_jPasswordField_SenhaKeyPressed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/*
		 * Set the Nimbus look and feel
		 */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(Janela_Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(Janela_Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(Janela_Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(Janela_Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/*
		 * Create and display the dialog
		 */
		//        java.awt.EventQueue.invokeLater(new Runnable() {
		//
		////            public void run() {
		////                Janela_Cadastro dialog = new Janela_Cadastro(new javax.swing.JFrame(), true);
		////                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
		////
		////                    @Override
		////                    public void windowClosing(java.awt.event.WindowEvent e) {
		////                        System.exit(0);
		////                    }
		////                });
		////                dialog.setVisible(true);
		////            }
		//        });
	}
	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton jButton_Cancelar;
	private javax.swing.JButton jButton_OK;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JPasswordField jPasswordField_Senha;
	private javax.swing.JPasswordField jPasswordField_SenhaConfirmacao;
	private javax.swing.JProgressBar jProgressBar1;
	private javax.swing.JTextField jTextField_EmailUsuario;
	private javax.swing.JTextField jTextField_NomeUsuario;
	// End of variables declaration//GEN-END:variables
}
